package com.ruoyi.mall.mq;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.mall.constant.OrderPaymentQueueExchangeContant;
import com.ruoyi.mall.domain.OrderMessage;
import com.ruoyi.mall.domain.Orders;
import com.ruoyi.mall.domain.Payment;
import com.ruoyi.mall.enums.OrderStatusEnum;
import com.ruoyi.mall.service.IOrdersService;
import com.ruoyi.mall.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;
@Slf4j
@Component
public class ReceiveService {
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IPaymentService paymentService;
    @Autowired
    private SendService sendService;

    @RabbitListener(queues =OrderPaymentQueueExchangeContant.ORDER_PAYMENT_QUEUE + "-${spring.profiles.active}", containerFactory = "batchRabbitListenerContainerFactory")
    public void directReceive(String message) {
        System.out.println(new Date()+" rabbit接收："+message);
        OrderMessage orderMessage = null;
        try {
            orderMessage = JSONObject.parseObject(message, OrderMessage.class);
        } catch (Exception e) {
            log.error("订单消息解析错误{}",message);
            return;
        }
        log.debug("接收到订单mq消息:{}",JSONObject.toJSONString(orderMessage));
        //查询订单状态
        Orders orders = ordersService.selectOrdersById(orderMessage.getOrderId());
        if(OrderStatusEnum.PENDING_PAYMENT.getCode().equals(orders.getStatus())){
            //查看订单支付状态
            Payment payment = paymentService.selectPaymentByOrderId(orderMessage.getOrderId());
            if(payment!=null){
                orders.setStatus(OrderStatusEnum.PAID.getCode());
                orders.setUpdateTime(DateUtils.getNowDate());
                ordersService.updateOrders(orders);
                return;
            }
        }
        Integer poll = orderMessage.getTimeQueue().poll();
        if(poll==null){
            //如果订单还未支付则取消订单
            int i = ordersService.cancelOrder(orderMessage.getOrderId());
            return;
        }
        try {
            sendService.sendDelayMessage(JSONObject.toJSONString(orderMessage),poll);
        } catch (UnsupportedEncodingException e) {
            log.error("订单号：{}mq消息发送失败",orderMessage.getOrderId());
        }
    }

}
